/**
 * 用户管理模块
 */
const User = require('../../models/User')
const { nanoid } = require('nanoid')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')


module.exports = function(router) {
    // 注册
    router.post('/register', async (req, res, netx) => {
        const { userName, passWord } = req.body
        const model = await User.findOne({
            where: {
                userName
            }
        })
        if (model)
            return res.send({ msg: '用户已经存在' })
        const screen_id = 'screen_' + nanoid(12)
        const user = await User.create({
            userName,
            passWord: bcrypt.hashSync(passWord, 8),
            screen_id
        })
        console.log(user.dataValues);
        res.send({ code: 200, msg: '注册成功！！ ！' })
    })
    // 登录
    router.post('/login', async (req, res, netx) => {
        const { userName, passWord } = req.body
        console.log(userName, passWord, '用户信息');
        const model = await User.findOne({
            where: {
                userName
            }
        })
        if (!model)
            return res.send({
                msg: '用户名不存在，请注册'
            })
        const passWordValid = bcrypt.compareSync(passWord, model.dataValues.passWord)
        if (!passWordValid)
            return res.send({
                code: 200,
                msg: '密码错误'
            })


        // 加密token，返回给客户端
        const token = jwt.sign({ userName }, 'screen')
        res.send({
            code: 200,
            data: {
                token: token
            }
        })
    })
}